//
//  MTLoginViewController.swift
//  MT
//
//  Created by ooops on 2019/12/12.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import YPNavigationBarTransition
import RxSwift
import RxDataSources
import Moya
import Result
import MTCategory
import IQKeyboardManagerSwift
import DeviceKit

class MTLoginViewController: BaseViewController {

    /// MTProvider
    private lazy var provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()
    
    private lazy var authProvider: MTProvider<DDCAuthAPI> = {
        let provider = MTProvider<DDCAuthAPI>()
        return provider
    }()
    
    private let disposeBag = DisposeBag()
    
    var isAppleValidating: Bool {
        return UserDefaults.AppValidate.isValidate.storedBool
    }
    
    /// logo
    lazy var wechatIcon: UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "Icon-60")
        imgView.contentMode = .scaleAspectFill
        imgView.clipsToBounds = true
        imgView.layer.cornerRadius = 12
        imgView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(loginController(didTapWechatIcon:)))
        imgView.addGestureRecognizer(tap)
        return imgView
    }()
    
    /// app名称
    lazy var wechatLabel: UILabel = {
        let label = UILabel()
        label.text = "觅颜"
        label.font = PingFangSCSemiboldFont(22)
        label.textColor = UIColor.text.x161616
        label.textAlignment = .center
        return label
    }()
    
    /// 登录按钮
    lazy var loginButton: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor.theme.main
        btn.setTitle("登录", for: .normal)
        btn.setTitleColor(UIColor.text.x161616, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 25
        btn.addTarget(self, action: #selector(loginViewController(didClickLoginButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 验证码登录按钮
    lazy var verifyPhoneButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("手机号验证码登录", for: .normal)
        btn.setTitleColor(UIColor(red: 47, green: 47, blue: 47), for: .normal)
        btn.titleLabel?.font = PingFangSCRegularFont(15)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(loginViewController(verifyPhoneLogin:)), for: .touchUpInside)
        return btn
    }()
    
    /// 忘记密码按钮
    lazy var forgetPwdButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("忘记密码？", for: .normal)
        btn.setTitleColor(UIColor(red: 47, green: 47, blue: 47), for: .normal)
        btn.titleLabel?.font = PingFangSCRegularFont(15)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(loginViewController(didClickResetButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 登录按钮
    lazy var userRegisterButton: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor.theme.main
        btn.setTitle("用户注册", for: .normal)
        btn.setTitleColor(UIColor.text.x161616, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 15
        btn.isHidden = true
        btn.addTarget(self, action: #selector(loginController(didClickRegisterButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 登录按钮
    lazy var userForgetButton: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor.theme.main
        btn.setTitle("忘记密码?", for: .normal)
        btn.setTitleColor(UIColor.text.x161616, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 15
        btn.isHidden = true
        btn.addTarget(self, action: #selector(loginController(didClickForgetButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 账号 TextField
    lazy var accTextField: UITextField = {
        let accTF = createTextField(withPlaceholder: "用户名/手机号")
        return accTF
    }()
    /// 密码 TextField
    lazy var pwdTextField: UITextField = {
        let pwdTF = createTextField(withPlaceholder: "请输入密码")
        pwdTF.keyboardType = .alphabet
        pwdTF.isSecureTextEntry = true
        return pwdTF
    }()
    
}

// MARK: ------------------ Override ----------------------
extension MTLoginViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        checkAppValidating()
    }
    
    private func setupUI() {
        initializeUI()
        if !isAppleValidating {
            initThirdPlatformUI()
        }
//        if !isAppleValidating {
//            appleValidatingInitUI()
//        }
        /// 正在审核中
        if isAppleValidating {
            appleValidatingInitUI()
        } else if !WXApi.isWXAppInstalled() {/// 也没安装微信
            appleValidatingInitUI()
        }
    }
    
    private func checkAppValidating() {
        if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
            authProvider.originRequest(.audit(version: version), callbackQueue: .main, progress: nil) { [weak self] (result, _) in
                guard let weakSelf = self else { return }
                switch result {
                case let .success(response):
                    if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int, code == 200 {
                        if (datas["result"] as? Bool) != nil {
                            UserDefaults.AppValidate.isValidate.store(value: datas["result"] as! Bool)
                            debugPrint("validate -------------: ", UserDefaults.AppValidate.isValidate.storedBool)
                            weakSelf.setupUI()
                        } else {
                            weakSelf.setupUI()
                        }
                    }
                    break
                case .failure(_):
                    weakSelf.setupUI()
                    break
                }
                
            }
        }
    }
    
    
    /// 创建文件
     func createFile(path: String) {
        var isDir: ObjCBool = false
        let existed = FileManager.default.fileExists(atPath: path, isDirectory: &isDir)
        if !isDir.boolValue && !existed {
            FileManager.default.createFile(atPath: path, contents: nil, attributes: nil)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enableAutoToolbar = true
        IQKeyboardManager.shared.enable = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = false
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }

}

// MARK: ------------------ UI 初始化 ----------------------
extension MTLoginViewController {
    
    private func initializeUI() {
        view.backgroundColor = UIColor.theme.background
        view.addSubview(wechatIcon)
        view.addSubview(wechatLabel)
        view.addSubview(accTextField)
        view.addSubview(pwdTextField)
        view.addSubview(loginButton)
        view.addSubview(verifyPhoneButton)
        view.addSubview(forgetPwdButton)
        
        
        wechatIcon.snp.makeConstraints { (make) in
            make.centerY.equalTo(view).offset(-200)
            make.centerX.equalTo(view)
            make.width.equalTo(74)
            make.height.equalTo(74)
        }
        
        wechatLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.bottom.equalTo(wechatIcon).offset(40)
        }
        
        accTextField.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(30)
            make.right.equalTo(self.view).offset(-30)
            make.top.equalTo(wechatLabel.snp.bottom).offset(40)
            make.height.equalTo(30)
        }
        
        pwdTextField.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(accTextField)
            make.top.equalTo(accTextField.snp.bottom).offset(30)
        }
        
        loginButton.snp.makeConstraints { (make) in
            make.top.equalTo(pwdTextField.snp.bottom).offset(40)
            make.centerX.equalTo(view)
            make.left.right.equalTo(accTextField)
            make.height.equalTo(50)
        }
        
        verifyPhoneButton.snp.makeConstraints { (make) in
            make.top.equalTo(loginButton.snp.bottom).offset(15)
            make.left.equalTo(accTextField)
        }
        
        forgetPwdButton.snp.makeConstraints { (make) in
            make.top.equalTo(loginButton.snp.bottom).offset(15)
            make.right.equalTo(accTextField)
            
        }
    }
    
    private func initThirdPlatformUI() {
        let leftLine = UIView()
        leftLine.backgroundColor = UIColor(hex:0xd8d8d8)
        self.view.addSubview(leftLine)
        
        let thirdLabel = UILabel()
        thirdLabel.text = "第三方登录"
        thirdLabel.font = PingFangSCRegularFont(15)
        thirdLabel.textColor = UIColor(hex:0x9b9b9b)
        thirdLabel.textAlignment = .center
        self.view.addSubview(thirdLabel)
        
        let rightLine = UIView()
        rightLine.backgroundColor = UIColor(hex:0xd8d8d8)
        self.view.addSubview(rightLine)
        
        leftLine.snp.makeConstraints { (make) in
            make.left.equalTo(20)
            make.top.equalTo(verifyPhoneButton.snp.bottom).offset(50)
            make.height.equalTo(0.5)
            make.right.equalTo(thirdLabel.snp.left).offset(-20)
        }
        
        thirdLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(leftLine)
        }
        
        rightLine.snp.makeConstraints { (make) in
            make.top.equalTo(leftLine)
            make.left.equalTo(thirdLabel.snp.right).offset(20)
            make.right.equalTo(self.view).offset(-20)
            make.height.equalTo(0.5)
        }
        
        let wxImage = UIImageView()
        wxImage.image = UIImage(named: "WeChat")
        wxImage.contentMode = .scaleAspectFill
        wxImage.clipsToBounds = true
        wxImage.layer.cornerRadius = 25
        wxImage.isUserInteractionEnabled = true
        wxImage.tag = 10000
        let wxTap = UITapGestureRecognizer(target: self, action: #selector(loginController(didTapWechatIcon:)))
        wxImage.addGestureRecognizer(wxTap)
        self.view.addSubview(wxImage)
        
//        let qqImage = UIImageView()
//        qqImage.image = UIImage(named: "QQ")
//        qqImage.contentMode = .scaleAspectFill
//        qqImage.clipsToBounds = true
//        qqImage.layer.cornerRadius = 25
//        qqImage.isUserInteractionEnabled = true
//        qqImage.tag = 10001
//        let qqTap = UITapGestureRecognizer(target: self, action: #selector(loginController(didTapWechatIcon:)))
//        qqImage.addGestureRecognizer(qqTap)
//        self.view.addSubview(qqImage)
//
//        let sinaImage = UIImageView()
//        sinaImage.image = UIImage(named: "xinlang")
//        sinaImage.contentMode = .scaleAspectFill
//        sinaImage.clipsToBounds = true
//        sinaImage.layer.cornerRadius = 25
//        sinaImage.isUserInteractionEnabled = true
//        sinaImage.tag = 10002
//        let sinaTap = UITapGestureRecognizer(target: self, action: #selector(loginController(didTapWechatIcon:)))
//        sinaImage.addGestureRecognizer(sinaTap)
//        self.view.addSubview(sinaImage)
        
        wxImage.snp.makeConstraints { (make) in
            make.width.height.equalTo(50)
            make.top.equalTo(leftLine.snp.bottom).offset(40)
            //make.left.equalTo(view).offset((ScreenWidth - 210) / 2)
            make.centerX.equalToSuperview()
        }
        
//        qqImage.snp.makeConstraints { (make) in
//            make.width.height.equalTo(wxImage)
//            make.top.equalTo(leftLine.snp.bottom).offset(40)
//            make.left.equalTo(wxImage.snp.right).offset(30)
//        }
//
//        sinaImage.snp.makeConstraints { (make) in
//            make.width.height.equalTo(wxImage)
//            make.top.equalTo(leftLine.snp.bottom).offset(40)
//            make.left.equalTo(qqImage.snp.right).offset(30)
//        }
    }
    
    private func appleValidatingInitUI() {
//        if !isAppleValidating {
//            return
//        }
//        wechatLabel.isHidden = true
//        wechatIcon.isHidden = true
        
        if UserDefaults.AppValidate.isValidate.storedBool {
            userRegisterButton.isHidden = false
            userForgetButton.isHidden = false
            verifyPhoneButton.isHidden = true
            forgetPwdButton.isHidden = true
            accTextField.isHidden = true
            pwdTextField.isHidden = true
            
            
            loginButton.snp.updateConstraints { (make) in
                make.top.equalTo(pwdTextField.snp.bottom).offset(60)
            }
        }
        let accTF = createTextField(withPlaceholder: "请输入账号")
        self.accTextField = accTF
        let pwdTF = createTextField(withPlaceholder: "请输入密码")
        pwdTF.isSecureTextEntry = true
        self.pwdTextField = pwdTF
        self.view.addSubview(accTF)
        self.view.addSubview(pwdTF)
        
        view.addSubview(userRegisterButton)
        view.addSubview(userForgetButton)
        
        accTF.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(30)
            make.right.equalTo(self.view).offset(-30)
            make.top.equalTo(wechatLabel.snp.bottom).offset(40)
            make.height.equalTo(30)
        }
        
        pwdTF.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(accTF)
            make.top.equalTo(accTF.snp.bottom).offset(30)
        }
        
        userRegisterButton.snp.makeConstraints { (make) in
            make.left.equalTo(pwdTF)
            make.top.equalTo(pwdTF.snp.bottom).offset(15)
            make.width.equalTo(80)
            make.height.equalTo(30)
        }
        
        userForgetButton.snp.makeConstraints { (make) in
            make.right.equalTo(pwdTF)
            make.top.equalTo(pwdTF.snp.bottom).offset(15)
            make.width.equalTo(120)
            make.height.equalTo(30)
        }
        
        if Device.current.isSimulator {
            self.accTextField.text = "zhangqiang_test"
            self.pwdTextField.text = "123456"
        }
    }
    
    private func createTextField(withPlaceholder placeholder: String) -> UITextField {
        let tf = UITextField()
        tf.font = PingFangSCRegularFont(15)
        tf.textColor = .black
        tf.tintColor = .black
        
        let astr = NSMutableAttributedString(string: placeholder)
        astr.setAttributes([NSAttributedString.Key.foregroundColor: UIColor(hex:0x9b9b9b)], range: NSMakeRange(0, astr.length))
        tf.attributedPlaceholder = astr
        
        let line = UIView()
        line.backgroundColor = UIColor(hex:0xd8d8d8)
        tf.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(tf)
            make.height.equalTo(0.5)
        }
        return tf
    }
    
}

// MARK: ------------------ 事件方法 ----------------------
@objc
extension MTLoginViewController {
    
    private func loginViewController(didClickLoginButton sender: UIButton) {
        login()
//        if isAppleValidating {
//            login()
//            return
//        } else if !WXApi.isWXAppInstalled() {/// 也没安装微信
//            login()
//            return
//        }
//        wechatLogin(loginType: .wechat)
    }
    
    private func loginViewController(verifyPhoneLogin sender: UIButton) {
        let vc = MTInputPhoneController()
        vc.titleStr = "手机验证码登录"
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    private func loginViewController(didClickResetButton sender: UIButton) {
        let vc = MTInputPhoneController()
        vc.titleStr = "手机验证码登录"
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    
    private func setRootViewController() {
        let vc: UIViewController = BaseTabBarViewController()
        UIApplication.mt_keyWindow?.rootViewController = vc
    }
    
    private func loginController(didTapWechatIcon tap: UITapGestureRecognizer) {
        if isAppleValidating {
            return
        } else if !WXApi.isWXAppInstalled() {/// 也没安装微信
            return
        }
        wechatLogin(loginType: tap.view?.tag == 10000 ? MTLoginType.wechat : tap.view?.tag == 10001 ? MTLoginType.qq : MTLoginType.sinaWeibo)
    }
    
    private func loginController(didClickRegisterButton sender: UIButton) {
        let c = MTUserRegisterViewController { (userName, password) in
            self.accTextField.text = userName
            self.pwdTextField.text = password
        }
        navigationController?.pushViewController(c, animated: true)
        
    }
    
    private func loginController(didClickForgetButton sender: UIButton) {
        let c = MTUserForgetViewController()
        navigationController?.pushViewController(c, animated: true)
    }
    
}

extension MTLoginViewController {
    
    private func wechatLogin(loginType: MTLoginType) {
        if !WXApi.isWXAppInstalled() {
            AlertManager.presentAlertView(message: "请先下载微信")
            return
        }
        /// 传递邀请者 id 参数
        var inviteID = ""
        OpenInstallSDK.defaultManager()?.getInstallParms(withTimeoutInterval: 5, completed: { [weak self] (appData) in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async {
                if appData?.data != nil {
                    if let inviteID = appData?.data["inviterId"] as? String, inviteID.count > 0 {
                        weakSelf.login(loginType: loginType, inviteID)
                    } else {
                        weakSelf.login(loginType: loginType)
                    }
                } else {
                    weakSelf.login(loginType: loginType)
                }
            }
        })
    }
    
    private func login(loginType: MTLoginType, _ inviteID: String? = nil) {
        MTUmengLogin.login(loginType, success: { [weak self] (result) in
            guard let weakSelf = self else { return }
            let originDict: [String : Any]  = result.originalResponse as! [String : Any]
            if loginType == .wechat {
                let requestParam: [String : Any] = ["accessToken" : result.accessToken!,
                                                    "nickname" : result.name!,
                                                    "openId" : result.openid!,
                                                    "province" : originDict["province"] ?? "",
                                                    "sex" : originDict["sex"] ?? 0,
                                                    "unionId" : result.unionId!]
                
                weakSelf.provider.rx.originRequest(.validation(requestParam)).subscribe(onNext: { [weak self] (result, isCache) in
                    guard let weakself = self else { return }
                    switch result {
                        
                    case .success(let response):
                        if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                                                
                            if code == 200 {
                                if let result = datas["result"] as? [String: Any] {
                                    weakself.loginReponse(with: result)
                                }
                            } else {
                                AlertManager.presentAlertView(message: "登录失败")
                            }
                        }
                        break
                        
                    case .failure(_):
                        AlertManager.presentAlertView(message: "登录失败")
                        break
                    }
                    
                }).disposed(by: weakSelf.disposeBag)
            }
        }) { (error) in
            
        }
    }
    
    private func login() {
        guard let acc = self.accTextField.text else {
            AlertManager.presentAlertView(message: "请输入账号")
            return
        }
        guard let pwd = self.pwdTextField.text else {
            AlertManager.presentAlertView(message: "请输入密码")
            return
        }
        
        if acc == "" {
            AlertManager.presentAlertView(message: "请输入账号")
            return
        } else if pwd == "" {
            AlertManager.presentAlertView(message: "请输入密码")
            return
        }
        
        var params: [String : Any] = ["mobile": acc,
                                    "password": pwd]
        
        /// 传递邀请者 id 参数
        OpenInstallSDK.defaultManager()?.getInstallParms(withTimeoutInterval: 5, completed: { [weak self] (appData) in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async {
                if appData?.data != nil {
                    if let inviteID = appData?.data["inviterId"] as? String, inviteID.count > 0 {
                        params.updateValue(inviteID, forKey: "inviterId")
                        weakSelf.userLogin(parameter: params)
                    } else {
                        weakSelf.userLogin(parameter: params)
                    }
                } else {
                    weakSelf.userLogin(parameter: params)
                }
            }
        })
        
    }
    /// 用户名密码登录
    private func userLogin(parameter: [String : Any]) {
        self.provider.originRequest(.login(parameter), callbackQueue: nil, progress: nil) { [weak self] (result, isCache) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    if code == 200 {
                         if let result = datas["result"] as? [String: Any] {
                             weakself.loginReponse(with: result)
                         }
                    } else if let msg = datas["message"] as? String {
                        DispatchQueue.main.async {
                            AlertManager.presentAlertView(message: msg)
                        }
                    }
                }
                break
                
            case .failure(_):
                DispatchQueue.main.async {
                    AlertManager.presentAlertView(message: "登录失败")
                }
                break
            }
        }
    }
    
    private func loginReponse(with result: [String:Any]) {
        /// 设置用户模型
        UserCenter.default.set(with: result)
        
        if let status = result["userStatus"] as? Int, let name = result["userName"] as? String, let pwd = result["userPassword"] as? String {
            switch status {
            /// 审核通过
            case 1:
                /// 弹窗
                IMLoginManager.login(name, pwd, complete: {
                    /// 设置用户模型
                    UserCenter.default.set(with: result)
                    AlertManager.presentAlertView(message: "登录成功", duration: 1) {
                        UserStatusNavigate.push(from: self, withUserStatus: status)
                    }
                    debugPrint("IM 登录成功")
                }) {
                    UserCenter.default.clear()
                    IMLoginManager.logout()
                    AlertManager.presentAlertView(message: "登录失败")
                    debugPrint("IM 登录失败")
                }
                break
            default:
                DispatchQueue.main.async {
                    UserStatusNavigate.push(from: self, withUserStatus: status)
                }
                break
            }
        } else {
            AlertManager.presentAlertView(message: "登录失败")
        }
    }
    
}
